package com.steerinfo.dil.config;

import com.alibaba.fastjson.JSONObject;
import com.steerinfo.dil.annotaion.LogAround;
import com.steerinfo.dil.annotaion.RequestLimit;
import com.steerinfo.framework.controller.RESTfulResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Web拦截器，拦截请求并校验
 */
@Slf4j
@Component
public class SessionInterceptor extends HandlerInterceptorAdapter {

    //暂时使用Map当做Redis缓存
    private static Map<String,Integer> redisUtil = new HashMap<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod hm = (HandlerMethod) handler;
        if(request.getAttribute("userId")==null || request.getAttribute("userName")==null){
            //无权访问
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            RESTfulResult result =new RESTfulResult("500", "无权访问", "无权访问");
            response.getWriter().write(JSONObject.toJSONString(result));
            return false;
        }
        //获取方法中的注解,看是否有该注解
        RequestLimit requestLimit = hm.getMethodAnnotation(RequestLimit.class);
        if(requestLimit != null){
            try{
                String userId = "" + request.getAttribute("userId");
                String userName = "" + request.getAttribute("userName");
                int seconds = requestLimit.seconds();
                int maxCount = requestLimit.maxCount();
                String methodName = hm.getMethod().getName();
                //获取请求体
                BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
                StringBuilder strBuilder = new StringBuilder();
                String inputStr;
                while ((inputStr = streamReader.readLine()) != null) {
                    strBuilder.append(inputStr);
                }
                Integer count = redisUtil.get(methodName+userId);
                if(count ==null || count < maxCount){
                    //未超出，+1
                    count = (count == null ?  0 : count+1);
                    redisUtil.put( methodName+userId, count);
                }else{
                    //超出访问次数
                    log.info("访问"+methodName+"方法过快，用户  ===> " + userId + " 且在   " + seconds + " 秒内超过最大限制  ===> " + maxCount + " 次数达到    ====> " + count);
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/json; charset=utf-8");
                    RESTfulResult result =new RESTfulResult("500", "访问过快，请稍后再试", "访问过快，请稍后再试");
                    response.getWriter().write(JSONObject.toJSONString(result));
                    return false;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return super.preHandle(request, response, handler);
    }

}
